import { useEffect, useRef, useState } from "react";
import { NodeProp } from "./ContainerProvider";

export default function CenterText(props: NodeProp) {
  const { text, textColor, width, height, position } = props;
  const [x, setX] = useState(position.x + width / 2);
  const [y, setY] = useState(position.y + height / 2 + 10);
  const textRef = useRef<SVGTextElement | null>(null);
  useEffect(() => {
    const textWidth = textRef.current?.getBoundingClientRect().width;
    const textHeight = textRef.current?.getBoundingClientRect().height;
    if (textWidth && textHeight) {
      setX(position.x + width / 2 - textWidth / 2);
      setY(position.y + height / 2 + 7.5);
    }
  }, [text, position.x, width, height, position.y]);
  return (
    <text
      x={x}
      y={y}
      fill={textColor ? textColor : "#fff"}
      ref={textRef}
      fontSize={30}
    >
      {text}
    </text>
  );
}
